/**
 * 
 */
package com.isaac.actm.domain.repository.jpa;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import com.isaac.actm.domain.pojo.User;
import com.isaac.actm.domain.repository.UserRepository;
import com.isaac.actm.domain.util.PagedQueryResult;

/**
 * @author ybak
 * 
 */
public class JPAUserRepositoryImpl extends JPAAbstractRepositoryImpl<User> implements UserRepository {
    public List<User> findAllUsers() {
        return jpaTemplate.find("select u from User u");
    }

    @Override
    @Transactional
    public void save(User entity) {
        if (entity.getId() == null) {
            entity.setCreateTime(new Date());
        }
        super.save(entity);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.isaac.actm.domain.repository.UserRepository#findUsers(int, int)
     */
    public PagedQueryResult findUsers(final int startingIndex, final int pageSize) {
        PagedQueryResult pagedResult = (PagedQueryResult) jpaTemplate.execute(new JpaCallback() {

            public PagedQueryResult doInJpa(EntityManager em) throws PersistenceException {
                Query query = em.createQuery("select u from User u");
                query.setFirstResult(startingIndex);
                query.setMaxResults(pageSize + 1);
                List results = query.getResultList();
                boolean more = results.size() > pageSize;
                if (more) {
                    results.remove(pageSize);
                }
                return new PagedQueryResult(results, more);
            }
        });
        return pagedResult;
    }

}
